<template>
  <avue-crud ref="userRef" :option="option" @refresh-change="getList" :data="data"
    :cell-style="cellStyle" :page="page" @size-change="sizeChange" @current-change="currentChange"
    @search-change="searchChange" @search-reset="searchReset">
    <template #menu="{ row, index, size }">
      <el-button type="primary" text @click="Prop_userCtl(row)">操作</el-button>
      <el-button type="primary" text @click="userDetail(row)">详情</el-button>

      <el-button type="success" text @click="userDeposit(row.userId, row.name)">手动上分</el-button>
      <el-button :type="row.status ? 'info' : 'danger'" text @click="mark(row.userId, row.status)">{{ row.status ?
        "取消标记" : "标记用户" }}</el-button>
      <el-button type="danger" v-if="row.isOnline" text @click="offLineUser(row.userId)">强制下线</el-button>
      <el-button type="info" text @click="checkInvite(row.userId)">查看下级</el-button>
    </template>
  </avue-crud>

  <DetailDialog :visible="detailVisible" v-model="detailVisible" :detailData="detail_data" @update:visible="detailVisible = $event" />


  <el-dialog v-model="userDepositVisible" title="手动上分" width="400" :show-close="false">
    <el-form ref="depositFormRef" :model="depositForm" :rules="depositRule" label-width="auto">
      <el-form-item label="用户ID">{{ depositForm.userId }}</el-form-item>
      <el-form-item label="用户名">{{ depositForm.name }}</el-form-item>
      <el-form-item>
        <el-radio-group v-model="userCtlFrom.upCtl">
          <el-radio-button label="上分金额"></el-radio-button>
          <el-radio-button label="赠送积分"></el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="输入值" prop="gold">
        <el-input type="number" v-model="depositForm.gold" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="cancelDeposit(depositFormRef)">取消</el-button>
        <el-button type="primary" @click="confirmDeposit(depositFormRef)">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>


  <el-dialog v-model="userCtlVisible">
    <el-from ref="form" :model="userCtlFrom">
      <el-form-item>
        <span>用户ID:{{ userCtlFrom.userId }}</span>
      </el-form-item>
      <el-form-item>
        <span>当前状态:{{ userCtlFrom.pageNum }}</span>
      </el-form-item>
      <el-form-item>
        <el-radio-group v-model="userCtlFrom.control">
          <el-radio-button label="送"></el-radio-button>
          <el-radio-button label="正常"></el-radio-button>
          <el-radio-button label="杀"></el-radio-button>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="送分金额" prop="changeGold">
        <el-input v-model="userCtlFrom.changeGold"></el-input>
      </el-form-item>
    </el-from>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="userCtlVisible = false">取消</el-button>
        <el-button type="primary" @click="comit_userCtl(userCtlFrom)">
          确认
        </el-button>
      </div>
    </template>
  </el-dialog>

</template>

<script setup>
import { onMounted, ref, reactive } from "vue";
import user from "@/options/user";
import DetailDialog from '@/components/DetailDialog.vue'; // 引入DetailDialog组件
import { ElMessageBox, ElMessage } from "element-plus";
import {
  getUserList,
  markUser,
  offlineUser,
  addUserGold,
  setGamePoint,
  setUserCtl,
  getUserCtl
} from "@/apis/admin";
import { useRouter } from "vue-router";

const cellStyle = ({ row, column, rowIndex, columnIndex }) => {
  let style = {
  };
  if(columnIndex > 17){
    return;
  }
  // style.backgroundColor = "#ffffff";
  // 随机一个0 1 2
  if (row.control === 0) {
  } else if (row.control === 1) {
    style.color = "#008000";
    style.backgroundColor = "#00800012";
  } else if (row.control === 2) {
    style.backgroundColor = "#f4433647";
  }

  return style;
};
const userCtlFrom = ref({
  userId: '000',
  control: '送',
  changeGold: 0,
  CurrentChangeGold: 0,
  pageNum: 0,
  upCtl:'上分金额'
})



const router = useRouter();
const depositFormRef = ref(null);
const depositForm = reactive({
  userId: 1,
  name: "",
  gold: "0",
});
const flowUserId = ref("");

const depositRule = reactive({
  gold: [{ required: true, message: "请输入金额", trigger: "blur" }],
});
const userDepositVisible = ref(false);
const userCtlVisible = ref(false);
const detailVisible = ref(false);
const cancelDeposit = (formEl) => {
  if (!formEl) return;
  formEl.resetFields();
  userDepositVisible.value = false;
};
const confirmDeposit = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (userCtlFrom.value.upCtl == '上分金额') {
      addUserGold
        .post("", { ...depositForm, gold: depositForm.gold * 100 })
        .then((res) => {
          if (res.code == 200) {
            ElMessage.success("上分成功!");
            formEl.resetFields();
            userDepositVisible.value = false;
            getList();
          }
        });
      } else if (userCtlFrom.value.upCtl == '赠送积分') {
        setGamePoint
        .post("", {...depositForm, gold: Number(depositForm.gold) })
        .then((res) => {
          if (res.code == 200) {
            ElMessage.success("赠送积分成功!");
            formEl.resetFields();
            userDepositVisible.value = false;
            getList();
          }else{
            ElMessage.error("赠送积分失败!");
            userDepositVisible.value = false;
          }
        });
      }else{
        ElMessage.error("操作失败!");
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};
onMounted(() => {
  getList();
});
const searchChange = (form, done) => {
  page.searchInfo = form;
  page.currentPage = 1;
  getList();
  done();
};
const searchReset = () => {
  page.searchInfo = {};
  page.currentPage = 1;
  getList();
};
const userDeposit = (id, username) => {
  depositForm.userId = id;
  depositForm.name = username;
  userDepositVisible.value = true;
};
const userDetail = (data) => {
  console.log('userDetail', data)
  detail_data.value = data;
  detailVisible.value = true;
  flowUserId.value = data.userId;
};
const detail_data = ref({});
const offLineUser = (userId) => {
  ElMessageBox.confirm("是否确定下线该用户?", "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    offlineUser.post("", { userId }).then((res) => {
      if (res.code == 200) {
        ElMessage.success("下线成功!");
        getList();
      }
    });
  });
};
const mark = (id, type) => {
  let msg = "";
  if (type == "1") {
    msg = "此操作将取消标记该用户, 是否继续?";
  } else {
    msg = "此操作将标记该用户, 是否继续?";
  }
  ElMessageBox.confirm(msg, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    markUser.post("", { userId: id, status: type == "1" ? 0 : 1 }).then((res) => {
      if (res.code == 200) {
        ElMessage.success("修改成功!");
        getList();
      }
    });
  });
};
const option = user;
const page = reactive({
  total: 0,
  searchInfo: {},
  currentPage: 1,
  pageSize: 10,
});
const sizeChange = (val) => {
  page.pageSize = val;
  getList();
};
const currentChange = (val) => {
  page.currentPage = val;
  getList();
};
const data = ref([]);
const getList = async () => {
  window.loading(1);
  if(page.searchInfo.registerTime){
    let startTime = new Date(page.searchInfo.registerTime[0]).getTime()
    let endTime = new Date(page.searchInfo.registerTime[1]).getTime()
    delete page.searchInfo.registerTime;
    page.searchInfo.registerStartTime = startTime / 1000
    page.searchInfo.registerEndTime = endTime / 1000
  }
  const res = await getUserList.post("", {
    pageSize: page.pageSize,
    page: page.currentPage,
    searchInfo: page.searchInfo,
    isrecharge: page.searchInfo.isrecharge == undefined ? 0 : page.searchInfo.isrecharge,
    orderKey: "created_at",
    orderType: "desc",
  });
  window.loading(0)
  if (res.code == 200) {
    page.total = res.data.total;
    data.value = res.data.list || [];
  }
};
const checkInvite = (id) => {
  router.push({
    path: "/subUser",
    query: {
      userId: id,
    },
  });
};
const formatDate = (date, cut) => {
  var date = new Date(date);
  var YY = date.getFullYear() + cut;
  var MM =
    (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + cut;
  var DD = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
  var hh = (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
  var mm = (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) + ":";
  var ss = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
  return YY + MM + DD + " " + hh + mm + ss;
};

/**
 * 
 * @param data 用户点杀操作
 */
const Prop_userCtl = async (data) => {
  userCtlVisible.value = true;
  window.loading(1)
  let _serverData = await getUserCtl.post("", { userId: data.userId })
  let serverData = _serverData.data;
  console.log(serverData)

  if (serverData.Control == 0) {
    userCtlFrom.value.control = '正常'
  } else if (serverData.Control == 2) {
    // control = 2
    userCtlFrom.value.control = '杀'
  } else {
    // control = 1
    userCtlFrom.value.control = '送'
  }
  userCtlFrom.value.CurrentChangeGold = serverData.CurrentChangeGold / 100
  userCtlFrom.value.changeGold = serverData.ChangeGold / 100;
  userCtlFrom.value.userId = data.userId;
  userCtlFrom.value.pageNum = (serverData.ChangeGold - serverData.CurrentChangeGold)/100
  window.loading(0)
}
const comit_userCtl = (data) => {
  console.log(data)
  window.loading(1)
  let control = 0;//正常
  if (data.control == '正常') {
    control = 0
  } else if (data.control == '杀') {
    control = 2
    if (Number(data.changeGold) > 0) {
      data.changeGold = -Number(data.changeGold)
    }
  } else {
    control = 1
    if (Number(data.changeGold) < 0) {
      data.changeGold = Math.abs(Number(data.changeGold))
    }
  }
  if (isNaN(Number(data.changeGold))) {
    data.changeGold = 0;
  }
  setUserCtl.post("", { userId: data.userId, control: control, changeGold: Number(data.changeGold) * 100 }).then((res) => {
    if (res.code == 200) {
      ElMessage.success("修改成功!");
    }
    window.loading(0)
    userCtlVisible.value = false;

  });
}
</script>
<style lang="scss" scoped>
.el-select .el-input {
  width: 130px;
}

.input-with-select .el-input-group__prepend {
  background-color: #fff;
}

.subtitle {
  width: 100%;
  border-radius: 4px;
  background: #f5f5f5;
  display: flex;
  justify-content: flex-start;
  align-items: center;
  font-size: 15px;
  font-weight: 600;
  box-sizing: border-box;
  padding: 8px 10px;
  margin: 10px 0;
}

.label {
  color: #666;
  font-size: 12px;
  padding-right: 8px;
}

.value {
  color: #333;
  font-size: 13px;
}
</style>
